# Create your views here.
import time
from datetime import * 
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.template import Context, loader
from django.template import RequestContext
from django.http import Http404
from django.shortcuts import render_to_response,get_object_or_404,render,get_list_or_404,redirect
from django.core.urlresolvers import reverse
from util.util import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from models import *


from tastypie.http import HttpUnauthorized, HttpForbidden
from tastypie.models import ApiKey, create_api_key
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash


import os
import chardet

def index(request):
    return render_to_response('index.html')

def login(request):
    #assert(False)
    dict = {'success':'sucessed'}
    modelresource = ModelResource()
    data = modelresource.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
    return modelresource.create_response(request, {
                    'success' : True,
                    'username' : data.get("name", "")
			}
                    )
#    return render_to_response('index.html',dict,context_instance=RequestContext(request))
    #return render_to_response('index.html',dict)

def PaginatorUtil(request,ItemList):
    paginator = Paginator(ItemList, CONSTANT_COUNT_PER_PAGE) # Show CONSTANT_COUNT_PER_PAGE ItemList per page
    page = request.GET.get('page')
    if not page:
        page = 1;
    try:
        page = int(page)
        Item_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        page=1
        Item_list = paginator.page(page)

    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        page=paginator.num_pages
        Item_list = paginator.page(paginator.num_pages)

    #set page range[first_page,last_page]
    last_page = page + CONSTANT_PAGE_RANGE - 1
    if last_page > paginator.num_pages:
        last_page = paginator.num_pages
    first_page = last_page - CONSTANT_PAGE_RANGE + 1

    if first_page < 1:
        first_page = 1
    page_range = range(first_page, last_page + 1)
    return {'page_range':page_range,'Item_list':Item_list}

def send_email(request):
    '''
        this method used to send email
    '''
    #email_text = get_web_link(request)
    email_text = str(request.session['email_text'])
    email = request.POST.get('email')
    if email:
        sendEmailTool(authInfo=EMAIL_INFO, to_list = [email], subject='System Info', htmlText=email_text)
    return render_to_response(request)
 
